﻿using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Data.Json;

namespace ApertiumNET
{
    public static class Apertium
    {
        private const string BaseURL = "http://api.apertium.org/json/";
        private const string GetPairs = BaseURL + "listPairs";
        private const string TranslateText = BaseURL + "translate?q={0}&langpair={1}%7C{2}";
       

        /// <summary>
        /// Translate string
        /// </summary>
        /// <param name="ApiKey">ApiKey. It can be null or empty. You can get one here 'http://api.apertium.org/register.jsp'</param>
        /// <param name="text">String to translate</param>
        /// <param name="from">Source Language</param>
        /// <param name="to">Destination Languaje</param>
        /// <returns>Translated text</returns>
        public async static Task<string> Translate(string ApiKey, string text, string from, string to)
        {
            //Prepare data
            text = text.Replace(" ", "%20");
            string url = "";
            if (string.IsNullOrEmpty(ApiKey))
            {
                string req = BaseURL + "translate?q={0}&langpair={1}%7C{2}";
                url = string.Format(req, text, from, to);
            }
            else
            {
                string req = BaseURL + "translate?key={0}&q={1}&langpair={2}%7C{3}";
                url = string.Format(req, ApiKey, text, from, to);
            }

            


            //Conect to service
            var client = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            });
                       

            //Parse response
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                try
                {
                    string result = await response.Content.ReadAsStringAsync();

                    JsonObject root = JsonObject.Parse(result);
                    JsonObject responseData = JsonObject.Parse(result).GetNamedObject("responseData");

                    int responseCode = (int)root.GetNamedNumber("responseStatus"); 
                    switch (responseCode)
                    {
                        case 200:
                            string translatedText = responseData["translatedText"].GetString();
                            return translatedText;
                        case 400:
                            //400 : Bad parameters. A compulsory argument is missing, or there is an argument with wrong format. A more accurate description can be found in responseDetails field.
                            throw new Exception("Bar parameters. " + root.GetNamedString("responseDetails"));
                        case 451:
                            //451 : Not supported pair. The translation engine can't translate with the requested language pair.
                            throw new Exception("Not supported pair. The translation engine can't translate with the requested language pair.");
                        case 452:
                            //452 : Not supported format. The translation engine doesn't recognize the requested format.
                            throw new Exception("Not supported format. The translation engine doesn't recognize the requested format");
                        case 500:
                            //500 : Unexpected error. An unexpected error happened. Depending on the error, a more accurate description can be found in responseDetails field.
                            throw new Exception(root.GetNamedString("responseDetails"));
                        case 552:
                            //552 : The traffic limit for your IP or your user has been reached.
                            throw new Exception("he traffic limit for your IP or your user has been reached. Get a Key in http://api.apertium.org/register.jsp ");
                        default:
                            //Unknow Error
                            throw new Exception("Error parsing response");
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            else
            {
                throw new Exception("HTTP Error " + response.StatusCode);
            }

        }

        /// <summary>
        /// Get a list of supporter languages pairs
        /// </summary>
        /// <returns>JsonArray with supported pairs</returns>
        public async static Task<JsonArray> ListPairs()
        {
            try
            {
                var client = new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                });

                HttpResponseMessage response = await client.GetAsync(GetPairs);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //Parsear cadena
                    string result = await response.Content.ReadAsStringAsync();
                    JsonObject root = JsonObject.Parse(result);
                    JsonArray array = root.GetNamedArray("responseData");
                    return array;
                }
                else
                {
                    throw new Exception("HTTP Error " + response.StatusCode);
                }
            }
            catch(Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}

